<template>
  <div class="player-wrap" v-if="playList.length > 0">
    <transition
      name="normal"
      @enter="enter"
      @after-enter="afterEnter"
      @leave="leave"
      @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img :src="currentSong.al.picUrl" width="100%" height="100%" />
        </div>
        <div class="top">
          <div class="back" @click="closeFullScreen">
            <i class="iconfont niceback icon-back"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle">
            <span v-for="(author, index) of currentSong.ar" :key="index">{{author.name}}</span>
          </h2>
        </div>
        <div
          class="middle"
          @touchstart.prevent="middleTouchStart"
          @touchmove.prevent="middleTouchMove"
          @touchend="middleTouchEnd"
        >
          <div class="middle-l" ref="cdMiddle">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdSpin">
                <img class="image" :src="currentSong.al.picUrl" />
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <scroll class="middle-r" ref="lyricList" :data="currentLyric && currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p
                  ref="lyricLine"
                  class="text"
                  :class="{ 'current': currentLyricLine === index }"
                  v-for="(line, index) in currentLyric.lines"
                  :key="index"
                >{{line.txt}}</p>
              </div>
              <p class="no-lyric" v-if="currentLyric === null">暂无歌词</p>
            </div>
          </scroll>
        </div>
        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{'active': currentShow === 'cd'}"></span>
            <span class="dot" :class="{'active': currentShow === 'lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time time-l">{{format(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
            </div>
            <span class="time time-r">{{format(duration)}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left" @click="changeMode">
              <i class="iconfont icon-sequence" :class="iconMode"></i>
            </div>
            <div class="icon i-left">
              <i @click="prevPlay" class="iconfont niceicon-16 icon-prev"></i>
            </div>
            <div class="icon i-center">
              <i @click="togglePlaying" class="iconfont icon-play" :class="playIcon"></i>
            </div>
            <div class="icon i-right">
              <i @click="nextPlay" class="iconfont niceicon-15 icon-text"></i>
            </div>
            <div class="icon i-right">
              <i class="iconfont niceshoucang1 icon-not-favorite"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="openFullScreen">
        <div class="icon">
          <img :class="cdSpin" :src="currentSong.al.picUrl" />
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"></h2>
          <p class="desc">
            <span v-for="(author, index) of currentSong.ar" :key="index">{{author.name}}</span>
          </p>
        </div>
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <i @click.stop="togglePlaying" class="iconfont icon-mini icon-play" :class="playIcon"></i>
          </progress-circle>
        </div>
        <div class="control">
          <i class="iconfont niceicon-5 icon-playlist"></i>
        </div>
      </div>
    </transition>
    <!-- audio -->
    <audio
      id="music-audio"
      ref="audio"
      :src="currentUrl"
      @playing="ready"
      @error="error"
      @timeupdate="updateTime"
      @pause="paused"
      @ended="end"
    ></audio>
  </div>
</template>

<script>
import ProgressBar from '@/components/progressBar/progressBar'
import ProgressCircle from '@/components/progressCircle/progressCircle'
import Scroll from '@/components/scroll/scroll'
import animations from 'create-keyframe-animation'
import LyricParser from 'lyric-parser'
import { mapGetters, mapMutations } from 'vuex'
import { prefixStyle } from '@/common/dom'
import { playMode } from '@/common/playConfig'
import { shuffle } from '@/common/common'

const transform = prefixStyle('transform')
const transitionDuration = prefixStyle('transitionDuration')

export default {
  data () {
    return {
      songReady: false,
      currentTime: 0,
      duration: 0,
      radius: 32,
      currentLyric: null,
      currentLyricLine: 0,
      currentShow: 'cd',
      playingLyric: ''
    }
  },
  components: {
    ProgressBar,
    ProgressCircle,
    Scroll
  },
  computed: {
    // cd旋转class添加
    cdSpin () {
      return this.playing ? 'play' : 'play pause'
    },
    iconMode () {
      return this.mode === playMode.sequence ? 'niceicon-19' : this.mode === playMode.loop ? 'niceicon-18' : 'niceicon-20'
    },
    // 播放按钮状态控制
    playIcon () {
      return this.playing ? 'niceicon-17' : 'niceicon-14'
    },
    // 进度条百分百
    percent () {
      return this.currentTime / this.duration
    },
    ...mapGetters([
      'fullScreen',
      'playList',
      'currentSong',
      'currentUrl',
      'playing',
      'currentIndex',
      'mode',
      'sequenceList'
    ])
  },
  methods: {
    firstPlay () {
      console.log('firstPlay')
      this.$refs.audio.play()
    },
    // 关闭播放界面
    closeFullScreen () {
      this.setFullScreen(false)
    },
    // 打开播放界面
    openFullScreen () {
      this.setFullScreen(true)
    },
    enter (el, done) {
      const { x, y, scale } = this.getPosAndScale()

      let animation = {
        0: {
          transform: `translate3d(${x}px, ${y}px,0) scale(${scale})`
        },
        60: {
          transform: `translate3d(0, 0, 0) scale(1.1)`
        },
        100: {
          transform: `translate3d(0, 0, 0) scale(1)`
        }
      }

      animations.registerAnimation({
        name: 'move',
        animation,
        presets: {
          duration: 400,
          easing: 'linear'
        }
      })

      animations.runAnimation(this.$refs.cdWrapper, 'move', done)
    },
    afterEnter () {
      animations.unregisterAnimation('move')
      this.$refs.cdWrapper.style.animation = ''
    },
    leave (el, done) {
      this.$refs.cdWrapper.style.transition = 'all 0.4s'
      const { x, y, scale } = this.getPosAndScale()
      this.$refs.cdWrapper.style[transform] = `translate3d(${x}px, ${y}px,0) scale(${scale})`
      this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave () {
      this.$refs.cdWrapper.style.transition = ''
      this.$refs.cdWrapper.style[transform] = ''
    },
    // 获取位置和缩放
    getPosAndScale () {
      const targetWidth = 40
      const paddingLeft = 40
      const paddingBottom = 30
      const paddingTop = 80
      const width = window.innerWidth * 0.8
      const scale = targetWidth / width
      const x = -(window.innerWidth / 2 - paddingLeft)
      const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
      return {
        x, y, scale
      }
    },
    // 播放，暂停播放
    togglePlaying () {
      if (!this.songReady) {
        return
      }
      this.setPlayingState(!this.playing)
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
    },
    // 上一首
    prevPlay () {
      if (!this.songReady) {
        return
      }
      if (this.playList.length === 1) {
        this.loopPlay()
      } else {
        let index = this.currentIndex - 1
        if (index === -1) {
          index = this.playList.length - 1
        }
        this.setCurrentIndex(index)
        let nextId = this.currentSong.id
        this._getSong(nextId)
        if (!this.playing) {
          this.togglePlaying()
        }
      }
      this.songReady = false
    },
    // 下一首
    nextPlay () {
      if (!this.songReady) {
        return
      }
      // 如果只有一首歌曲
      if (this.playList.length === 1) {
        this.loopPlay()
      } else {
        let index = this.currentIndex + 1
        if (index === this.playList.length) {
          index = 0
        }
        this.setCurrentIndex(index)
        let nextId = this.currentSong.id
        this._getSong(nextId)
        if (!this.playing) {
          this.togglePlaying()
        }
      }
      this.songReady = false
    },
    loopPlay () {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
    },
    ready () {
      clearTimeout(this.timer)
      this.songReady = true
    },
    paused() {
      this.setPlayingState(false)
      if (this.currentLyric) {
        this.currentLyric.stop()
      }
    },
    error () {
      clearTimeout(this.timer)
      this.songReady = true
    },
    end () {
      if (this.mode === playMode.loop) {
        this.loopPlay()
      } else {
        this.nextPlay()
      }
    },
    // 设置歌曲时间
    updateTime (e) {
      this.duration = e.target.duration
      this.currentTime = e.target.currentTime
    },
    // 滑动进度条改变播放进度
    onProgressBarChange (percent) {
      const currentTime = this.duration * percent
      this.$refs.audio.currentTime = currentTime
      if (!this.playing) {
        this.togglePlaying()
      }
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },
    // 改变播放模式
    changeMode () {
      const mode = (this.mode + 1) % 3
      this.setPlayMode(mode)
      let list = null
      if (mode === playMode.random) {
        list = shuffle(this.sequenceList)
      } else {
        list = this.sequenceList
      }
      this.resetCurrentIndex(list, this.currentIndex)
      this.setPlayList(list)
    },
    middleTouchStart (e) {
      this.touch.initiated = true
      // 用来判断是否是一次移动
      this.touch.moved = false
      const touch = e.touches[0]
      this.touch.startX = touch.pageX
      this.touch.startY = touch.pageY
    },
    middleTouchMove (e) {
      if (!this.touch.initiated) {
        return
      }
      const touch = e.touches[0]
      const deltaX = touch.pageX - this.touch.startX
      const deltaY = touch.pageY - this.touch.startY
      if (Math.abs(deltaY) > Math.abs(deltaX)) {
        return
      }
      if (!this.touch.moved) {
        this.touch.moved = true
      }
      const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
      const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      this.$refs.lyricList.$el.style[transitionDuration] = 0
      this.$refs.cdMiddle.style.opacity = 1 - this.touch.percent
      this.$refs.cdMiddle.style[transitionDuration] = 0
    },
    middleTouchEnd () {
      if (!this.touch.moved) {
        return
      }
      let offsetWidth
      let opacity
      if (this.currentShow === 'cd') {
        if (this.touch.percent > 0.1) {
          offsetWidth = -window.innerWidth
          opacity = 0
          this.currentShow = 'lyric'
        } else {
          offsetWidth = 0
          opacity = 1
        }
      } else {
        if (this.touch.percent < 0.9) {
          offsetWidth = 0
          this.currentShow = 'cd'
          opacity = 1
        } else {
          offsetWidth = -window.innerWidth
          opacity = 0
        }
      }
      const time = 300
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`
      this.$refs.cdMiddle.style.opacity = opacity
      this.$refs.cdMiddle.style[transitionDuration] = `${time}ms`
      this.touch.initiated = false
    },
    // 时分秒转换
    format (interval) {
      interval = interval | 0
      const minute = this.prefixInteger(interval / 60 | 0)
      const second = this.prefixInteger(interval % 60)
      return `${minute}:${second}`
    },
    // 补 0
    prefixInteger (num, n = 2) {
      let len = num.toString().length
      while (len < n) {
        num = '0' + num
        len++
      }
      return num
    },
    resetCurrentIndex (list, song) {
      let index = list.findIndex((item) => {
        return item.id === this.currentSong.id
      })
      this.setCurrentIndex(index)
    },
    // 获取歌曲url
    _getSong (id) {
      this.$api.getSongUrl(id).then((res) => {
        if (res.data[0].url) {
          this.setCurrentUrl(res.data[0].url)
        } else {
          this.songReady = true
          this.$toast({
            message: '可能要vip，换一首吧'
          })
        }
      })
    },
    // 获取歌曲歌词
    _getLyric (id) {
      this.$api.getSongLyric(id).then((res) => {
        let lyric = res.lrc.lyric
        this.currentLyric = new LyricParser(lyric, this.handleLyric)
        if (this.playing) {
          this.currentLyric.play()
        }
      }).catch(() => {
        this.currentLyric = null
        this.playingLyric = '暂无歌词'
        this.currentLyricLine = 0
      })
    },
    // LyricParser 回调
    handleLyric ({ lineNum, txt }) {
      this.currentLyricLine = lineNum
      if (lineNum > 5) {
        let lineEl = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricList.scrollToElement(lineEl, 1000)
      } else {
        this.$refs.lyricList.scrollTo(0, 0, 1000)
      }
      this.playingLyric = txt
    },
    autoPlayAudio() {
      console.log(this.$wx)
      this.$wx.config({
          debug: false,
          appId: '',
          timestamp: 1,
          nonceStr: '',
          signature: '',
          jsApiList: []
      })
      this.$refs.audio.load()
      this.$refs.audio.play()
      this.$wx.ready(function() {
        document.getElementById('music-audio').load()
        document.getElementById('music-audio').play()
      })
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN',
      setPlayingState: 'SET_PLAYING_STATE',
      setCurrentIndex: 'SET_CURRENT_INDEX',
      setCurrentUrl: 'SET_CURRENT_URL',
      setPlayMode: 'SET_PLAY_MODE',
      setPlayList: 'SET_PLAYLIST'
    })
  },
  created () {
    this.touch = {}
  },
  watch: {
    currentSong (newSong, oldSong) {
      if (newSong.id === oldSong.id) {
        return
      }
      if (this.currentLyric) {
        this.currentLyric.stop()
      }
      this._getSong(newSong.id)
      this._getLyric(newSong.id)
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.autoPlayAudio()
      }, 1000)
    },
    currentUrl (newUrl, oldUrl) {
      if (newUrl === oldUrl) {
        return
      }
      this.songReady = false
      if (this.currentLyric) {
        this.currentLyric.stop()
        // 重置为null
        this.currentLyric = null
        this.currentTime = 0
        this.playingLyric = ''
        this.currentLineNum = 0
      }
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.songReady = true
      }, 5000)
      this.$nextTick(() => {
        this.autoPlayAudio()
      })
    },
    playing (newPlaying) {
      if (!this.songReady) {
        return
      }
      const audio = this.$refs.audio
      this.$nextTick(() => {
        newPlaying ? audio.play() : audio.pause()
      })
    },
    fullScreen(newVal) {
      if (newVal) {
        setTimeout(() => {
          this.$refs.lyricList.refresh()
        }, 20)
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../assets/styles/variable';
@import '../../assets/styles/mixin';

.player-wrap {
  .normal-player {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 150;
    background: $color-background;

    .background {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      opacity: 0.6;
      filter: blur(20px);
    }

    .top {
      position: relative;
      margin-bottom: 25px;

      .back {
        position: absolute;
        top: 0;
        left: 6px;
        z-index: 50;

        .icon-back {
          display: block;
          padding: 9px;
          font-size: $font-size-large-x;
          color: $color-theme;
          transform: rotate(-90deg);
        }
      }

      .title {
        width: 70%;
        margin: 0 auto;
        line-height: 40px;
        text-align: center;
        no-wrap();
        font-size: $font-size-large;
        color: $color-text;
      }

      .subtitle {
        line-height: 20px;
        text-align: center;
        font-size: $font-size-medium;
        color: $color-text;

        span {
          &:after {
            content: '/';
            margin: 0 0.06rem;
          }

          &:last-child:after {
            content: '';
          }
        }
      }
    }

    .middle {
      position: fixed;
      width: 100%;
      top: 80px;
      bottom: 170px;
      white-space: nowrap;
      font-size: 0;

      .middle-l {
        display: inline-block;
        vertical-align: top;
        position: relative;
        width: 100%;
        height: 0;
        padding-top: 80%;

        .cd-wrapper {
          position: absolute;
          left: 10%;
          top: 0;
          width: 80%;
          height: 100%;

          .cd {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            border: 10px solid rgba(255, 255, 255, 0.1);
            border-radius: 50%;

            &.play {
              animation: rotate 20s linear infinite;
            }

            &.pause {
              animation-play-state: paused;
            }

            .image {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
        }

        .playing-lyric-wrapper {
          width: 80%;
          margin: 30px auto 0 auto;
          overflow: hidden;
          text-align: center;

          .playing-lyric {
            height: 20px;
            line-height: 20px;
            font-size: $font-size-medium;
            color: $color-text-l;
          }
        }
      }

      .middle-r {
        display: inline-block;
        vertical-align: top;
        width: 100%;
        height: 100%;
        overflow: hidden;

        .lyric-wrapper {
          width: 80%;
          margin: 0 auto;
          overflow: hidden;
          text-align: center;

          .text {
            line-height: 32px;
            color: $color-text-l;
            font-size: $font-size-medium;

            &.current {
              color: $color-text;
            }
          }

          .no-lyric {
            line-height: 40px;
            margin-top: 60%;
            color: #ffffff;
            font-size: $font-size-medium;
          }
        }
      }
    }

    .bottom {
      position: absolute;
      bottom: 50px;
      width: 100%;

      .dot-wrapper {
        text-align: center;
        font-size: 0;

        .dot {
          display: inline-block;
          vertical-align: middle;
          margin: 0 4px;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: $color-text-l;

          &.active {
            width: 20px;
            border-radius: 5px;
            background: $color-text-ll;
          }
        }
      }

      .progress-wrapper {
        display: flex;
        align-items: center;
        width: 100%;
        margin: 0px auto;
        padding: 0.1rem 0.3rem;

        .time {
          color: $color-text;
          font-size: $font-size-small;
          flex: 0 0 30px;
          line-height: 30px;
          width: 30px;

          &.time-l {
            text-align: left;
          }

          &.time-r {
            text-align: right;
          }
        }

        .progress-bar-wrapper {
          flex: 1;
          margin: 0 0.2rem;
        }
      }

      .operators {
        display: flex;
        align-items: center;

        .icon {
          flex: 1;
          color: $color-theme;

          &.disable {
            color: $color-theme-d;
          }

          i {
            font-size: 30px;
          }
        }

        .i-left {
          text-align: right;
        }

        .i-center {
          padding: 0 20px;
          text-align: center;

          i {
            font-size: 40px;
          }
        }

        .i-right {
          text-align: left;
        }

        .icon-favorite {
          color: $color-sub-theme;
        }
      }
    }

    &.normal-enter-active, &.normal-leave-active {
      transition: all 0.4s;

      .top, .bottom {
        transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32);
      }
    }

    &.normal-enter, &.normal-leave-to {
      opacity: 0;

      .top {
        transform: translate3d(0, -100px, 0);
      }

      .bottom {
        transform: translate3d(0, 100px, 0);
      }
    }
  }

  .mini-player {
    width: 100%;
    height: 1.3rem;
    background: #141E30;
    background: -webkit-linear-gradient(to right, #243B55, #141E30);
    background: linear-gradient(to right, #243B55, #141E30);
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 180;
    padding: 0rem 0.3rem;

    // display: none;
    &.mini-enter-active, &.mini-leave-active {
      transition: all 0.4s;
    }

    &.mini-enter, &.mini-leave-to {
      opacity: 0;
    }

    .icon {
      width: 0.8rem;
      height: 0.8rem;
      margin-right: 0.2rem;

      img {
        width: 40px;
        width: 0.8rem;
        height: 0.8rem;
        border-radius: 50%;

        &.play {
          animation: rotate 10s linear infinite;
        }

        &.pause {
          animation-play-state: paused;
        }
      }
    }

    .text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      flex: 1;
      line-height: 20px;
      overflow: hidden;

      .name {
        margin-bottom: 2px;
        no-wrap();
        font-size: $font-size-medium;
        color: $color-text;
      }

      .desc {
        no-wrap();
        font-size: $font-size-small;
        color: $color-text-d;

        span {
          &:after {
            content: '/';
            margin: 0 0.06rem;
          }

          &:last-child:after {
            content: '';
          }
        }
      }
    }

    .control {
      width: 0.6rem;
      margin-left: 0.4rem;

      .icon-play, .icon-pause, .icon-playlist {
        font-size: 30px;
        color: #ff5b73;
      }

      .icon-mini {
        font-size: 32px;
        position: absolute;
        left: 0rem;
        top: 0rem;
      }
    }
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>
